package com.lj.universalframework.utils


import android.content.Context
import android.net.ConnectivityManager
import android.view.LayoutInflater
import androidx.databinding.ViewDataBinding
import androidx.viewbinding.ViewBinding
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.ParameterizedType


object CommonUtil {

    fun <T> getClass(t: Any): Class<T> {
        // 通过反射 获取父类泛型 (T) 对应 Class类
        return (t.javaClass.genericSuperclass as ParameterizedType)
            .actualTypeArguments[0]
                as Class<T>
    }

    /**
     * 通过反射机制动态创建 ViewDataBinding 对象
     * @param target Any
     * @param inflater LayoutInflater?
     * @return ViewDataBinding?
     */
    fun createBinding(target: Any, inflater: LayoutInflater?): ViewDataBinding? {
        val clazz: Class<*> = target.javaClass
        if (clazz.genericSuperclass !is ParameterizedType) {
            return null
        }
        val parameterizedType = clazz.genericSuperclass as ParameterizedType?
        val typeArguments = parameterizedType!!.actualTypeArguments
        if (typeArguments.isEmpty()) {
            return null
        }
        typeArguments.forEach {
            if (it is Class<*> && ViewDataBinding::class.java.isAssignableFrom(it)) {
                try {
                    val method = it.getDeclaredMethod(
                        "inflate",
                        LayoutInflater::class.java
                    )
                    return method.invoke(null, inflater) as ViewDataBinding
                } catch (e: NoSuchMethodException) {
                    e.printStackTrace()
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                } catch (e: InvocationTargetException) {
                    e.printStackTrace()
                }
            }
        }
        return null
    }

    /**
     * 检查网络状态
     */
    fun isNetworkConnected(context: Context): Boolean {
        val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            ?: return false
        val networkinfo = manager.activeNetworkInfo
        return !(networkinfo == null || !networkinfo.isAvailable)
    }
}